/**
 * @author zj
 * @desc:
 * @date: 2024/9/7 07
 */
export class WebSocketClient {
  ws;
  url;

  constructor(url) {
    this.url = url;
    this.connect();
  }
  connect() {
    this.ws = new WebSocket(this.url);
    this.ws.onopen = function () {
      console.log("WebSocket 连接成功。");
    };
    this.ws.onmessage = function (event) {
      console.log("收到服务器消息：", event.data);
    };
    this.ws.onerror = function (event) {
      console.error("WebSocket 连接出现错误：", event);
    };
    this.ws.onclose = function () {
      console.log("WebSocket 连接已经关闭。");
    };
  }

  send(message) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(message);
    } else {
      console.error("[WebSocket] 未连接");
    }
    //this.ws.send(message);
  }
}
